package com.example.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.common.annotation.LogAnno;
import com.example.common.constant.Const;
import com.example.common.result.Result;
import com.example.controller.base.BaseController;
import com.example.entity.KeyResults;
import com.example.entity.Objective;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ptuDai
 * @since 2022-04-17
 */
@RestController
@RequestMapping("/key-results")
public class KeyResultsController extends BaseController {

    @GetMapping("/list/{objectiveId}")
    @PreAuthorize("hasAnyRole('user','admin','superAdmin')")
    public Result list(@PathVariable @NotNull Integer objectiveId){
        List<KeyResults> list = keyResultsService.list(new QueryWrapper<KeyResults>().eq("objective_id",objectiveId));
        return Result.ok().data(list);
    }
    @LogAnno(operateType = "查看关键结果信息")
    @GetMapping("/info/{id}")
    @PreAuthorize("hasAnyRole('user','admin','superAdmin')")
    public Result info(@PathVariable @NotNull Integer id){
        KeyResults keyResults = keyResultsService.getById(id);
        return Result.ok().data(keyResults);
    }
    @LogAnno(operateType = "新增/编辑关键结果")
    @PostMapping("/save")
    @PreAuthorize("hasAnyRole('user','admin','superAdmin')")
    @Transactional(rollbackFor = Exception.class)
    public Result save(@RequestBody KeyResults keyResults){
        if (keyResults.getId() != null) {
            keyResultsService.update(keyResults,new UpdateWrapper<KeyResults>().set("status",0).set("complete_time",null).eq("id",keyResults.getId()));
            return Result.update();
        }else {
            keyResultsService.save(keyResults);
            return Result.created();
        }
    }
    @LogAnno(operateType = "删除关键结果")
    @DeleteMapping("/del/{id}")
    @PreAuthorize("hasAnyRole('user','admin','superAdmin')")
    @Transactional(rollbackFor = Exception.class)
    public Result del(@PathVariable Integer id){
        keyResultsService.removeById(id);
        return Result.deleted();
    }
    @LogAnno(operateType = "改变关键结果完成状态")
    @PostMapping("/changeStatus")
    @PreAuthorize("hasAnyRole('user','admin','superAdmin')")
    @Transactional(rollbackFor = Exception.class)
    public Result changeStatus(@RequestBody KeyResults keyResults){
        if (keyResults.getStatus()){
            keyResults.setCompleteTime(LocalDateTime.now());
            keyResultsService.updateById(keyResults);
            List<KeyResults> list = keyResultsService.list(new QueryWrapper<KeyResults>().select("id").eq("status", 0).in("id", keyResultsService.list(new QueryWrapper<KeyResults>().eq("objective_id", keyResults.getObjectiveId())).stream().map(KeyResults::getId).collect(Collectors.toList())));
            if (list.isEmpty()){
                Objective objective = new Objective();
                objective.setId(keyResults.getObjectiveId());
                objective.setStatus(Const.STATUS_COMPLETE);
                objective.setCompleteTime(LocalDateTime.now());
                objectiveService.updateById(objective);
            }
        }else {
            keyResultsService.update(new UpdateWrapper<KeyResults>().set( "complete_time",null).set("status",keyResults.getStatus()).eq("id",keyResults.getId()));
        }
        return Result.update();
    }
}
